<template>
  <div class="flex">
    <div>
      <div style="margin-left: 46px" v-if="showTitle"> 图片上传</div>
      <el-upload ref="uploadFile" :auto-upload="true" :before-upload="beforeUpload" :http-request="uploadAction"
                 :limit="1"
                 :on-exceed="handleExceed" :show-file-list="false" action='#'
                 class="avatar-uploader" style="width: 100%;">
        <img v-if="bannerUrl" :src="bannerUrl" class="avatar"/>
        <el-icon v-else class="avatar-uploader-icon">
          <Plus/>
        </el-icon>
      </el-upload>
    </div>

  </div>
</template>

<script lang="ts" setup>
import {computed, reactive, ref, toRefs, PropType} from 'vue';
import {ElMessage} from 'element-plus'
import type {UploadRawFile, UploadFile} from 'element-plus';
import {Plus} from '@element-plus/icons-vue'
import {uploadImage} from "@/services/components";
import Compressor from 'compressorjs';
import {useI18n} from "vue-i18n";
import {cloneDeep} from 'lodash';
import {getImage} from "@/utils/common";
import {CompressionOption, TypeImage} from "@/components/upload/enum";

const {t} = useI18n()
const emit = defineEmits([] as any);
const props = defineProps({
  // url参数
  imageUrl: {
    type: String,
    default: () => {
      return ''
    },
  },
  // 是否需要显示文字（图片上传)
  showTitle: {
    type: Boolean,
    default: () => {
      return true
    },
  },
  // 是否需要同时上传一张限定宽高的压缩图（默认false）
  isCompression: {
    type: Boolean,
    default: () => {
      return true
    },
  },
  // 配置项与compressionOption相同
  smallImgOption: {
    type: Object || Object as PropType<CompressionOption>,
    default: () => {
      return {
        width: 50,
        height: 50
      }
    },
  },
  // 缩略图配置项，详情查看CompressionOption
  compressionOption: {
    type: Object || Object as PropType<CompressionOption>,
    default: () => {
      return {
        quality: 0.6
      }
    },
  },
})

const initData = reactive({
  bannerUrl: computed(() => {
    return cloneDeep(props.imageUrl)
  }),
  fileList: [],
  obg: {} as TypeImage | any
})

const {bannerUrl} = toRefs(initData)


const uploadFile: any = ref('')


const handleExceed = () => {
  if (initData.fileList.length >= 1) {
    ElMessage.error(t('js.only'))
    return;
  }
}

const beforeUpload = (file: UploadRawFile) => {
  const type = ['image/jpeg', 'image/jpg', 'image/png']
  if (type.indexOf(file.type) === -1) {
    ElMessage.error(t('js.uploaded'))
    return false
  } else if (file.size / 1024 / 1024 > 50) {
    ElMessage.error(t('js.size'))
    return false
  }
  return true
}

const uploadAction = (option: any) => {

  new Compressor(option.file, {
    ...props.compressionOption,
    // The compression process is asynchronous,
    // which means you have to access the `result` in the `success` hook function.
    success(result) {
      // The third parameter is required for server
      console.log(result)
      let param = new FormData();
      param.append('file', result, result.name);
      uploadimage(param, 'bigImage')
      // 是否需要同时上传一张限定宽高的压缩图（默认false）
      if (props.isCompression) {
        new Compressor(option.file, {
          ...props.compressionOption,
          ...props.smallImgOption,
          success(result) {
            let param = new FormData();
            param.append('file', result);
            uploadimage(param, 'smallImage')
          },
        });
      }
    },
    error(err) {
      console.log(err.message);
    },
  });
}

const uploadimage = (param: any, name: string) => {
  uploadImage(param).then((res: any) => {
    if (res && res.code == 200) {
      initData.obg[name] = res.data
      emit('handlerUpload', initData.obg)
      // initData.bannerUrl = URL.createObjectURL(option.file!);
      // initData.bannerUrl = getImage(res.data)
      // emit('update:')
      uploadFile.value.clearFiles()
    }
  })
}


</script>

<style lang="scss" scoped>
.canvasDiv {
  position: relative;
  border: 3px solid red;
  //height: 400px;
  //width: 400px;
  margin-top: 50px;
  margin-left: 100px;
  z-index: 0;
}

.canvasImg {
  width: 100%;
  height: 100%;
  z-index: 1;
  position: absolute;
}

#canvas {
  position: absolute;
  // border: 1px solid green;
  z-index: 2;
}

.grid_position_graph {
  display: inline-block;
  background-color: #eaedef;
  line-height: 25px;
  vertical-align: middle;
  padding-left: 15px;
  padding-right: 15px;
  margin-left: 20px;
  margin-right: 20px;
  border: solid 1px #bcbcbf;
  border-radius: 6px;
  font-size: 12px;
  font-weight: normal;
}
</style>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.colorr {
  display: flex;
  width: 100%;
  justify-content: space-around;
}
</style>
